/**
 * https://leetcode.cn/problems/longest-univalue-path/submissions/582548924/
 * 687.最长同值路径
 * medium 陈贝纯 2024.11.23
 * dfs
 */


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int num=0;
    int dfs(TreeNode* root){
        if(root==nullptr)
        return -1;
        int l=0;
        int r=0;
        l=1+dfs(root->left);
        r=1+dfs(root->right);
        if(root->left&&root->left->val!=root->val)
        l=0;
        if(root->right&&root->right->val!=root->val)
        r=0;
        num=max(num,l+r);
        return max(r,l);
    }
    int longestUnivaluePath(TreeNode* root) {
        dfs(root);
        return num;
    }
};